<?php
class RM_Admin_PickupDropoffController extends RM_Controller
{

    // locations
    public function locationlistJsonAction()
    {
        $offset = $this->_getParam('start');
        $count = $this->_getParam('limit');
        $sort = $this->_getParam('sort', 'id');
        if ($sort == 'units') {
            $sort = 'global';
        }        
        $direction = $this->_getParam('dir', 'DESC');
        $filters = $this->_getParam('filter', array());

        $order = $sort . ' ' . $direction;
        $dao = new RM_PickupDropoff();

        $total = $dao->filterAll($order, null, null, $filters)->count();
        $rows = $dao->filterAll($order, $count, $offset, $filters);
        
        $data = array();
        foreach ($rows as $row) {
            $dataRow = $row->toArray();
            $data[] = $dataRow;
        }

        $json = new stdClass;
        $json->total = $total;
        $json->data = $data;

        return array(
            'data' => $json
        );
    }

    public function locationupdateJsonAction(){
        if ($this->_getParam('name')!=""){
            $id = $this->_getParam('id');
            $gmaps = $this->_getParam('gmaps');
            $enabled = $this->_getParam('enabled');

            if ($gmaps != "false") $gmaps = 1;
            if ($enabled != "false") $enabled = 1;
            
            $data = array(
                "name"=>$this->_getParam('name'),
                "address1"=>$this->_getParam('address1'),
                "address2"=>$this->_getParam('address2'),
                "address3"=>$this->_getParam('address3'),
                "city"=>$this->_getParam('city'),
                "postcode"=>$this->_getParam('postcode'),
                "country"=>$this->_getParam('country'),
                "state"=>$this->_getParam('state'),
                "gmaps"=>$gmaps,
                "enabled"=>$enabled,
                "units"=>trim($this->_getParam('units'),",")
            );

            $dao = new RM_PickupDropoff();

            if ($id){
                // update
                $dao->update($data, "id='".$id."'");
            } else {
                // insert
                $dao->insert($data);
            }

            return array(
            'data' => array('success' => 'true', 'msg' => '')
            );

        }

    }

    public function locationdeleteJsonAction(){
        $ids = $this->_getParam('ids', array());
        $model = new RM_PickupDropoff();

        foreach ($ids as $id) {
            $row = $model->find($id)->current();
            if ($row === null) continue;
            $row->delete();
        }

        return array(
            'data' => array('success' => true)
        );
    }

    public function loadlocationJsonAction(){
        $id = $this->_getParam('id');
        $json = new stdClass;
        if ($id) {
            $dao = new RM_PickupDropoff();
            $data = $dao->getLocationData($id)->toArray();

            $criteria = new RM_Unit_Search_Criteria(array(), true);
            $dao = new RM_Units;
            $total = $dao->getAll($criteria)->count();


            $json->totalUnits = $total;
            $json->settings = $data;
        }

        return array(
            'data' => $json
        );
    }


    // location pricing

    public function pricelistJsonAction(){
        $offset = $this->_getParam('start');
        $count = $this->_getParam('limit');
        $sort = $this->_getParam('sort', 'id');
        if ($sort == 'units') {
            $sort = 'global';
        }
        $direction = $this->_getParam('dir', 'DESC');
        $filters = $this->_getParam('filter', array());

        $order = $sort . ' ' . $direction;
        $dao = new RM_PickupDropoffPrices();

        $total = $dao->filterAll($order, null, null, $filters)->count();
        $rows = $dao->filterAll($order, $count, $offset, $filters);

        $data = array();
        foreach ($rows as $row) {
            $dataRow = $row->toArray();
            $data[] = $dataRow;
        }

        $json = new stdClass;
        $json->total = $total;
        $json->data = $data;

        return array(
            'data' => $json
        );
    }

    // locations
    public function pricelocationsJsonAction()
    {
        $dao = new RM_PickupDropoff();

        $total = $dao->getAll()->count();
        $rows = $dao->getAll()->toArray();

        $data = array();
        foreach($rows as $row){
            $data[] = array("id"=>$row['id'],'name'=>$row['name']);
        }

        return array(
            'data' => $data
        );
    }

    public function pricelocationdeleteJsonAction(){
        $ids = $this->_getParam('ids', array());
        $model = new RM_PickupDropoffPrices();

        foreach ($ids as $id) {
            $row = $model->find($id)->current();
            if ($row === null) continue;
            $row->delete();
        }

        return array(
            'data' => array('success' => true)
        );
    }

    function priceupdateJsonAction()
    {
        $dataJson = $this->_getParam('data', '[]');
        $data = Zend_Json::decode($dataJson);

        $model = new RM_PickupDropoffPrices;
        foreach ($data as $row){
            if (!$row['id']){
                // insert
                unset ($row['id']);
                $model->insert($row);
            } else {
                // update
                $model->update($row, "id = '".$row['id']."'");
            }

        }

        return array('data' => array('success' => true));
    }

    // configuration

    public function configJsonAction(){

        $model = new RM_PickupDropoffConfig;
        $data = $model->get()->toArray();

        return array(
            'data' => $data
        );
    }

    public function updateconfigJsonAction(){
        $data = array(
            "priceoption" => $this->_getParam('priceoption'),
            "default_price" => $this->_getParam('default_price')
        );
        $model = new RM_PickupDropoffConfig;
        $model->update($data, "id = '1'");

        return array('data' => array('success' => true));
    }

    // reservation edit
    
    public function reservationloadJsonAction(){
        $id = $this->_getParam('id'); // get the reservation ID
        $unit_id = $this->_getParam('unit_id'); // get the unit ID

        $data = new stdClass();
        $data->id = $id;
        $data->unit_id = $unit_id;

        $model = new RM_ReservationPickupDropoff();
        $data = $model->getByReservation($data);

        return array(
            'data' => array('id_pickup'=>$data[0]->id_pickup,'id_dropoff'=>$data[0]->id_dropoff)
        );
    }

    public function reservationupdateJsonAction(){
        $id = $this->_getParam('id'); // get the reservation ID
        $id_pickup = $this->_getParam('location_id_pickup');
        $id_dropoff = $this->_getParam('location_id_dropoff');
        $model = new RM_ReservationPickupDropoff();

        $data = new stdClass();
        
        $data->id = $id;
        $data->id_pickup = $id_pickup;
        $data->id_dropoff = $id_dropoff;
        $this->_reservationUpdate($data);

        return array('data' => array('success' => true));
    }

    private function _reservationUpdate($data){

        // check the reservation id is present
        $reservationDetailID = $data->id;
        if ($reservationDetailID == null) {
            return false;
        }

        // get the current reservation
        $reservationModel = new RM_Reservations();
        $reservation = $reservationModel->find($reservationDetailID)->current();
        if ($reservation == null) {
            return false;
        }

        // get the current reservation details
        $reservationDetailsModel = new RM_ReservationDetails();
        $reservationDetail = $reservationDetailsModel->getAllByReservation($reservation)->current();

        // calculate the new price
        $priceModel = new RM_PickupDropoffPrices();
        $priceData = $priceModel->calculate($data);

        // load any saved data for this reservation...
        $model = new RM_ReservationPickupDropoff();
        $savedData = $model->getByReservationID($reservationDetailID)->toArray();$savedData = $savedData[0];

        // update or save the p/u location data

        // convert the data object into an array for update/insert
        $dataArray = array();
        foreach($data as $key=>$value){
            $dataArray[$key] = $value;
        }

        if (isset($savedData) && $savedData['id']!=""){
            // update
            unset($dataArray['id']);
            $model->update(array("id_pickup"=>$data->id_pickup,"id_dropoff"=>$data->id_dropoff),"id='".$data->id."'");

        } else {
            // insert
            $model->insert($dataArray);
        }

        // update the reservation summary

        $summaryModel = new RM_ReservationSummary();

        // get the $rowID
        $rowModel = new RM_ReservationSummary();
        $SummaryRow = $rowModel->fetchByReservationDetail($reservationDetail, RM_Module_PickupDropoff::SUMMARY_TYPE);
        $SummaryRow = $SummaryRow[0];

        if (!isset($SummaryRow->id)){
            $data = array(
                'reservation_id' => null,
                'reservation_detail_id' => $reservationDetail->id,
                'type' => RM_Module_PickupDropoff::SUMMARY_TYPE,
                'row_id' => 1,
                'value' => 1,
                'total_amount' => $priceData['price'],
                'name' => $this->_translate->_('Admin.PickupDropoff.Main', 'name')
            );
            $summaryRow = $summaryModel->createRow($data);
            $summaryRow->save();

        } else {
            $summaryRow = $summaryModel->update(array("total_amount"=>$priceData['price']),"reservation_detail_id='".$reservationDetail->id."' AND type='".RM_Module_PickupDropoff::SUMMARY_TYPE."'");
        }
        
        

        return true;
    }
}